package mume.infoRetriever;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ArtistInfoHandler extends DefaultHandler {

	private String name;
	private String largeImage;
	private String artistInfo;
	
	private boolean similarOpen;
	private boolean tagsOpen;
	private boolean nameOpen;
	private boolean summaryOpen;
	private boolean largeImageOpen;
		
	public ArtistInfoHandler() {
		super();
	}
	
	public String getName() {
		return name;
	}
	public String getImage() {
		return largeImage;
	}
	public String getArtistInfo() {
		return artistInfo;
	}

	public String toString() {
		return name + " (" + largeImage + ")" + "\n info: " + artistInfo;
	}
	
	public void startDocument() throws SAXException {
		summaryOpen = false;
		similarOpen = false;
		nameOpen = false;
		largeImageOpen = false;
		
		//should be changed while parsing
		name = "Name unknown";
		largeImage = "Image Not Found";
		artistInfo = "No Extra Info Found";
	}
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		if(!similarOpen && !tagsOpen && localName.equals("name")) {
			nameOpen = true;
		} else if(localName.equals("similar")) {
			similarOpen = true;
		} else if(localName.equals("tags")){
			tagsOpen = true;
		} else if(localName.equals("summary")){
			summaryOpen = true;
		} else if(localName.equals("image") && atts.getValue("size").equals("large")){
			largeImageOpen = true;
		}
	}
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(!similarOpen && !tagsOpen && localName.equals("name")) {
			nameOpen = false;
		} else if(localName.equals("similar")){
			similarOpen = false;
		} else if(localName.equals("tags")){
			tagsOpen = false;
		} else if(localName.equals("summary")) {
			summaryOpen = false;
		} else if(localName.equals("image")){
			largeImageOpen = false;
		}
	}
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if(nameOpen || summaryOpen || largeImageOpen){
			String help = "";
			for (int i = start; i < start + length; i++) {
			    switch (ch[i]) {
			    case '\\':
			    	help = help.concat("\\\\");
				break;
			    case '"':
			    	help = help.concat("\\\"");
				break;
			    case '\n':
			    	help = help.concat("\\n");
				break;
			    case '\r':
			    	help = help.concat("\\r");
				break;
			    case '\t':
			    	help = help.concat("\\t");
				break;
			    default:
			    	help = help.concat(Character.toString(ch[i]));
				break;
			    }
			}

			if(nameOpen)
				name = help;
			else if(largeImageOpen)
				largeImage = help;
			else
				artistInfo = help;
		}
	}
	
	public void endDocument() throws SAXException {
		summaryOpen = false;
		similarOpen = false;
		nameOpen = false;
		largeImageOpen = false;
	}

}
